package com.glodon.controller;

import com.glodon.service.UserService;
import com.glodon.utils.EncryptUtil;
import com.glodon.utils.RedisTemplateUtil;
import com.glodon.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wanghy-h on 2017-10-25.
 */
@RestController
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, String userName, String password, boolean cookie) {
        try {
            if (cookie) {
                password = EncryptUtil.decrypt(password);
            }
            User user = userService.login(userName, password);
            if (user == null) {
                return "fail";
            }
            request.getSession().setAttribute("userID", user.getId());
            request.getSession().setAttribute("username", userName);
            RedisTemplateUtil redisTemplateUtil = new RedisTemplateUtil(redisTemplate);
            redisTemplateUtil.set("user",user);

            logger.info("user is  {}", user.toString());
            return "success";
        } catch (Exception e) {
            logger.error("login has error:",e);
            return "fail";
        }
    }

    @RequestMapping("/login/encrypt")
    public String encryptPassword(String password) {
        String encryptPassword = EncryptUtil.encrypt(password);
        return encryptPassword;
    }
}
